package appBord

import grails.converters.JSON
import groovy.sql.Sql
import org.codehaus.groovy.grails.web.json.JSONObject

class AppBordNodeMonitorController {


    def dataSource

    def index() {

        def boardId = Long.parseLong(params?.boardId)

        def appBordNodeList = AppBordNodeMonitor.findAllByBoardId(boardId)
        def appBordAlarm = AppBordAlarm.list().groupBy {it.alarmNo}
        def appBordType = AppBordType.list().groupBy {it.typeNo}
        def appBordTypeList = AppBordType.list()

        List<AppBordGroup> container = new ArrayList<AppBordGroup>() //有容器
        Map<String,List<AppBordNodeMonitor>> containerNodes = new HashMap<String,List<AppBordNodeMonitor>>()
        def nodeSingle = new ArrayList<AppBordNodeMonitor>() //无容器节点
        def nodeLine = new ArrayList<Map>()
        def alarmNodes = new HashMap<String,Map>()
        def typeColorMap = new HashMap();
        appBordNodeList.each {node->
            def group = AppBordGroup.findByGroupNo(node.groupNo)
            if(group){//有容器分组节点
                if( group && !container.contains(group)){
                    container.add(group)
                    containerNodes.put(node.groupNo,new ArrayList<AppBordNodeMonitor>())
                }
                containerNodes.get(node.groupNo).add(node);
            }else{//无容器分组节点
                nodeSingle.add(node)
            }
            if(node.relaNodeNo){
                def relaNode = AppBordNodeMonitor.findByNodeNo(node.relaNodeNo);
                if(relaNode){
                    nodeLine.add([from:node.nodeName?:node.nodeNo,to:relaNode.nodeName?:relaNode.nodeNo ,line:node.relaLine])
                }
            }
            if(node.alarmNo){
                def alarmInstance = appBordAlarm.get(node.alarmNo)?appBordAlarm.get(node.alarmNo)[0]:null;
                if(alarmInstance){
                    alarmNodes.put( "${node.nodeName?:node.nodeNo}" ,
                            [alarmColor:alarmInstance.alarmColor,
                            alarmInfo:node.alarmInfo?:alarmInstance.alarmName,
                            alarmFlash:alarmInstance.alarmFlash])
                }
            }
            if(node.typeNo){
                def typeColor = appBordType.get(node.typeNo)?appBordType.get(node.typeNo)[0]:null;
                if(typeColor){
                    typeColorMap.put(node.nodeName?:node.nodeNo,typeColor.typeColor)
                }
            }
        }
        def result =  [container:container,
                       containerNodes:containerNodes,
                       nodeSingle:nodeSingle,
                       appBordType:appBordType,
                       nodeLine:nodeLine,
                       alarmNodes:alarmNodes,
                       typeColorMap:typeColorMap,
                       appBordTypeList:appBordTypeList]
        render result as JSON
    }


    def fullScreen(){
        def  model = index()
        model
    }

    def show(){
        def boardId = Long.parseLong(params?.boardId)

        def appBoardInfo = AppBordInfo.get(boardId)
        def sql = """
        select NODE_NO,  NODE_NAME
          from (${appBoardInfo.dataSql}) tb
         where not exists (select 1 from app_bord_node_monitor ta where tb.NODE_NO = ta.NODE_NO) 
        """
        def relaLineList = [[value:"FoldLink",label:"折线 ↳"],[value:"Link",label: "直线 →"],
                            [value:"FoldLink1",label:"折线 ∟"],[value:"Link1",label: "直线 —"]]
        def appBordGroup = AppBordGroup.list()
        def appBordType = AppBordType.list()
        def iconList = iconList()
        def appBordAlarm = AppBordAlarm.list()
        def eqpList = new Sql(dataSource).rows(sql.toString())
        def relaList = AppBordNodeMonitor.list()
        render(view: "/appBord/appBordNodeMonitor/update.gsp",
                model: [ relaLineList:relaLineList,appBordGroup:appBordGroup,
                         appBordType:appBordType,iconList:iconList,
                         appBordAlarm:appBordAlarm,eqpList:eqpList,
                         relaList:relaList,
                         boardId:boardId])
    }

    def nodeOption(){
        println params
        def nodeNo = params?.nodeNo
        def appBordNodeList =  AppBordNodeMonitor.list(sort:"groupNo",order: "asc")
        def nodeInstance = AppBordNodeMonitor.newInstance()
        if(nodeNo){
            appBordNodeList = AppBordNodeMonitor.findAll("from AppBordNodeMonitor as a where a.nodeNo !='${nodeNo}' order by a.groupNo asc" )
            nodeInstance = AppBordNodeMonitor.findByNodeNo(nodeNo)
        }
        def r = [relaNodes:appBordNodeList,nodeInstance:nodeInstance]
        //println r as JSON
        render r as JSON
    }

    def update(){
        def resultJson = JSONObject.newInstance()
        resultJson.put("statusCode",200)
        resultJson.put("message","操作成功")
        //resultJson.put("closeCurrent",true)

        def nodeName = params.name
        def groupNo = params.groupNo
        def typeNo = params.typeNo
        def relaNodeNo = params.relaNodeNo
        def relaLine = params.relaLine
        def nodeImg = params.nodeImg
        def alarmNo = params.alarmNo
        def alarmInfo = params.alarmInfo
        def nodeDesc = params.nodeDesc
        def action = params.actionUrl
        try {
            def nodeNo = params.nodeNo
            def appBordNode = AppBordNodeMonitor.findByNodeNo(nodeNo)
            if(!appBordNode){
                appBordNode = AppBordNodeMonitor.newInstance()
                if(groupNo){
                    def max = AppBordNodeMonitor.executeQuery("select max(x),max(y) from AppBordNodeMonitor as a where a.groupNo= '${groupNo}' ")
                    if(max){
                        def x = max[0][0];
                        def y = max[0][1];
                        if(x<= 0){
                            x = 0
                        }else{
                            x = x-50
                        }

                        if(y<= 0){
                            y = 0
                        }else{
                            y = y-50
                        }

                        appBordNode.x = x
                        appBordNode.y = y
                    }
                }
            }
            appBordNode.nodeNo = nodeNo
            appBordNode.nodeName = nodeName
            appBordNode.groupNo = groupNo
            appBordNode.typeNo = typeNo
            appBordNode.relaNodeNo = relaNodeNo
            appBordNode.relaLine = relaLine
            appBordNode.alarmNo = alarmNo
            appBordNode.alarmInfo = alarmInfo
            appBordNode.nodeImg = nodeImg
            appBordNode.width = 80
            appBordNode.height = 30
            appBordNode.nodeDesc = nodeDesc
            appBordNode.actionUrl = action
            appBordNode.boardId = Long.parseLong(params.boardId?:-1)
            appBordNode.save(flush: true)
        }catch (Exception e){
            resultJson.put("statusCode",-200)
            resultJson.put("message","操作失败")
            e.printStackTrace()
        }finally{
            render resultJson.toString()
        }
    }

    def iconList(){
        def result = []
        def dir = grailsApplication.getMainContext().servletContext.getRealPath("/")+"appBord/img"
        //def dir = grailsApplication.getMainContext().getResource("appBord/img").getFile()
        //println "dirs:${dir}"
        def file = new File(dir)
        file?.eachFileRecurse {it ->
            if(it.isFile()){
                def name = it.getName()
                result.add("appBord/img/${name}")
            }
        }
        result
    }

    def chLocation(){

        def resultJson = JSONObject.newInstance()
        resultJson.put("statusCode",200)
        resultJson.put("message","操作成功")
        resultJson.put("closeCurrent",true)


        try {
            def nodeNo = params.nodeNo
            def x = Float.parseFloat(params.x?:0)
            def y = Float.parseFloat(params.y?:0)
            if(nodeNo){
                def appBordNode = AppBordNodeMonitor.findByNodeNo(nodeNo)
                if(!appBordNode){
                    appBordNode = AppBordNodeMonitor.findByNodeName(nodeNo)
                }
                appBordNode.setX(x)
                appBordNode.setY(y)
                appBordNode.save(flush: true)
            }
        }catch (Exception e){
            resultJson.put("statusCode",-200);
            resultJson.put("message","移动位置失败");
            e.printStackTrace()
        }finally{
            render resultJson.toString()
        }
    }

    def deleteNode(){
        def resultJson = JSONObject.newInstance()
        resultJson.put("statusCode",200)
        resultJson.put("message","操作成功")
        resultJson.put("closeCurrent",true)

        try {
            def nodeNo = params.nodeNo
            if(nodeNo){

                def appBordNode = AppBordNodeMonitor.findByNodeNo(nodeNo)
                if(!appBordNode){
                    appBordNode = AppBordNodeMonitor.findByNodeName(nodeNo)
                }

                def relaNodes = AppBordNodeMonitor.findAllByRelaNodeNo(appBordNode.nodeNo)
                relaNodes?.each {it ->
                    it.relaNodeNo = null;
                    it.save(flush: true)
                }

                appBordNode.delete(flush: true)
            }
        }catch (Exception e){
            resultJson.put("statusCode",-200);
            resultJson.put("message","删除节点失败");
            e.printStackTrace()
        }finally{
            render resultJson.toString()
        }
    }

    def updateNode(){
        def resultJson = JSONObject.newInstance()
        resultJson.put("statusCode",200)
        resultJson.put("message","操作成功")
        resultJson.put("closeCurrent",true)

        try {
            def nodeNo = params.nodeNo
            def width = Float.parseFloat(params.width?:"46")
            def height =Float.parseFloat(params.height?:46*0.618)
            if(nodeNo){
                def appBordNode = AppBordNodeMonitor.findByNodeNo(nodeNo)
                if(!appBordNode){
                    appBordNode = AppBordNodeMonitor.findByNodeName(nodeNo)
                }
                appBordNode.setWidth(width)
                appBordNode.setHeight(height)

                appBordNode.save(flush:true)
            }
        }catch (Exception e){
            resultJson.put("statusCode",-200);
            resultJson.put("message","修改节点失败");
            e.printStackTrace()
        }finally{
            render resultJson.toString()
        }
    }

    def nodeDesc(){
        def resultJson = JSONObject.newInstance()
        resultJson.put("statusCode",200)
        resultJson.put("message","操作成功")
        resultJson.put("closeCurrent",true)

        try{
            def nodeNo = params.nodeNo
            if(nodeNo){
                def appBordNode = AppBordNodeMonitor.findByNodeNo(nodeNo)
                if(!appBordNode){
                    appBordNode = AppBordNodeMonitor.findByNodeName(nodeNo)
                }
                resultJson.put("message",appBordNode?.nodeDesc)
            }
        }catch (Exception e){
            resultJson.put("statusCode",-200);
            resultJson.put("message","查询失败");
            e.printStackTrace()
        }finally{
            //println resultJson.toString()
            render resultJson.toString()
        }
    }

    def test(){
        def a = JSON.parse("""{
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
}
""")

        println a
    }
}
